<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Tree;
use think\Cookie;

class Goods extends Frontend
{

    protected $noNeedLogin = ['index','detail'];
    protected $noNeedRight = '*';
    protected $layout = 'mall';

    public function _initialize()
    {
        parent::_initialize();
        //获取brand BEGIN
        $mapBrand = [
            'switch' => 1,
        ];
        $brandData = model('app\common\model\Brand')
            ->field('id,name,image')
            ->where($mapBrand)
            ->order('top_switch desc,weigh asc')
            ->select();

        //$brand = addWebSiteUrl($brandData, ['image']);
        $this->view->assign('brand',$brandData);
        //获取brand END

        //cart BEGIN
        $cart = Cookie::has('mall_cart') ? json_decode(Cookie::get('mall_cart'),true) : [];
        $this->view->assign('cart',$cart);
        //cart END

        //获取商品cate BEGIN
        $tree = Tree::instance();
        $tree->init(collection( model('app\common\model\Category')->where('type','goods')->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $category = $tree->getTreeArray(0);
        $this->view->assign('category',$category);
        //获取商品cate END
    }

    public function index($cate = 0,$type = 0,$brand = 0)
    {
        $search = $this->request->get('search',0);

        //获取商品cate BEGIN
        $tree = Tree::instance();
        $tree->init(collection( model('app\common\model\Category')->where('type','goods')->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $categoryList = $tree->getTreeArray(0);
        $this->view->assign('categoryList',$categoryList);
        //获取商品cate END

        //获取商品type BEGIN
        $typeList = model('app\common\model\GoodsType')
            ->field('id,name')
            ->order('updatetime desc')
            ->select();
        $this->view->assign('typeList',$typeList);
        //获取商品type END

        //获取商品 BEGIN
        $map = [
            'market_switch' => 1,
        ];
        if ($type) $map['goods_type_id'] = $type;
        if ($brand) $map['brand_id'] = $brand;
        if ($search) $map['name'] = ['LIKE',"%{$search}%"];
        if ($cate) {
            //获取子id
            $child = $tree->getChildrenIds($cate);
            array_push($child,$cate);
            $map['category_id'] = ['in',$child];
        }

        $goodsData = model('app\common\model\Goods')
            ->field('id,name,brief,price,costprice,mktprice,image,stock,top_switch')
            ->where($map)
            ->order('updatetime desc')
            ->paginate(12);
        $goods = addWebSiteUrl($goodsData, ['image']);
        $this->view->assign('goods',$goods);
        $page = $goods->render();
        $this->view->assign('page', $page);
        //获取商品 END
        return $this->view->fetch();
    }


    public function detail($id)
    {

        $map = [
            'market_switch' => 1,
            'id'    => $id,
        ];

        $data = model('app\common\model\Goods')
            ->field('id,name,mktprice,price,brief,stock,image,images,intro_content,spes_desc,params')
            ->with(['products'=>function($query){
                $query->field('id,goods_id,price,is_defalut,image,sn,stock,spes_desc');
            }])
            ->where($map)
            ->find();
        $data['images'] = explode(',',$data['images']);

        //推荐BEGIN
        $topList = model('app\common\model\Goods')
            ->field('id,name,mktprice,price,brief,stock,image')
            ->where([
                'market_switch' => 1,
            ])
            ->limit(5)
            ->orderRaw("RAND()")
            ->select();
        $this->view->assign('topList', $topList);
        //推荐END

        //获取商品type BEGIN
        $typeList = model('app\common\model\GoodsType')
            ->field('id,name')
            ->order('updatetime desc')
            ->select();
        $this->view->assign('typeList',$typeList);
        //获取商品type END


        if ($data) {
            //图片相对地址转绝对地址 begin
            /*if ($data['image']) {
                $data['image'] = getRealUrl($data['image']);
            }

            if ($data['images']) {
                $images = explode(',', $data['images']);
                foreach ($images as $k => $v) {
                    $images[$k] = getRealUrl($v);
                }
                $data['images'] = $images;
            }*/

            //编辑框图片转绝对地址
            /*$intro_images = [];
            if (isset($data['intro_content'])) {
                preg_match_all('/(?<=img.src=").*?(?=")/', $data['intro_content'], $out, PREG_PATTERN_ORDER);      //正则匹配img标签的src属性，返回二维数组
                if (!empty($out)) {
                    foreach ($out as $v) {
                        foreach ($v as $j) {
                            $url = getRealUrl($j);
                            $intro_images[] = $url;
                            $data['intro_content'] = str_replace($j, $url, $data['intro_content']);   //替换相对路径为绝对路径
                        }
                    }
                }
            }
            $data['intro_images'] = $intro_images;*/
            //图片处理 end

            //多规格参数
            //$data['spes_desc'] = unserialize($data['spes_desc']);
            $params = unserialize($data['params']);
            if (is_array($params)) {
                foreach ($params as $k => $v) {
                    if (is_array($v)) {
                        $params[$k] = implode('|', $v);
                    }
                }
            }
            $data['params'] = $params;
            foreach ($data['products'] as $k => $v){
                if ($v['is_defalut'] == 1){
                    $data['products_id'] = $v['id'];
                }
            }
        }
        $this->view->assign('data', $data);
        return $this->view->fetch();
    }

}
